//是否在选课阶段
var isElective = undefined;

//记录当前选择的“课程周期”
var electiveWeek = 0;

//记录当前选择的“课程几次”
var electiveTime = 0;

var electiveCourseId=0;

var scheduleId = 0;

$(function () {
    isElective = $("#is_elective").val();
    //初始化学生课程表
    initialCourseTable();

    $('#elective_layout').layout('setRegionToolVisibleState', {region: 'south', visible: false});

    //设置“南布局”的标题
    if (isElective == 'true') {
        $("#elective_layout").layout("panel", "south")
            .panel("setTitle", "可选课程列表(未选择课表)");
    } else {
        $("#elective_layout").layout("panel", "south")
            .panel("setTitle", "课程学习情况(未选择课表)");
    }

    //初始化“南布局”内容
    initialSouthLayoutContent();

    var adminClaszs;
    var studyClaszs;

    $.getJSON('clasz/all-admin-claszs', function (data) {
        adminClaszs = data;
    });
    $.getJSON('clasz/all-study-claszs', function (data) {
        studyClaszs = data;
    });

    $.ajax({
        type: "GET",
        url: "student/idno/" + $("#student_id_no").val(),
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data) {
                if (data.teachingClass != 0) {
                    $("#teaching_class").val(studyClaszs[data.teachingClass].name);
                }
                if (data.executiveClass != 0) {
                    $("#admin_class").val(adminClaszs[data.executiveClass].name);
                }
            }
        }
    });


    //打印课表功能
    var print = $("#print");
    if (print) {
        print.click(function () {
            $(createPrintPage("个人学生课表", $("#course_table"))).jqprint();
        });
    }
});

function createPrintPage(strPrintName, printDatagrid) {
    var printAreaElement = "<div id='printArea'>";

    //加载标题
    printAreaElement += "<div style='text-align: center;font-size: 25px;'><b>个人学生课表</b></div>";

    //加载时间、姓名信息
    printAreaElement += "<div style='text-align: right;'><label>姓名:</label><span><b>" + $("#student_name").val() + "</b></span>"
    printAreaElement += "<label style='margin-left: 15px'>行政班:</label><span><b>" + $("#admin_class").val() + "</b></span>";
    printAreaElement += "<label style='margin-left: 15px'>教学班:</label><span><b>" + $("#teaching_class").val() + "</b></span>";
    var nowDate = new Date();
    var nowYear = nowDate.getFullYear();
    var nowMonth = nowDate.getMonth();
    var nowDay = nowDate.getDate();
    printAreaElement += "<label style='margin-left: 15px'>打印时间:</label><span><b>" + nowYear + '-' + (nowMonth + 1) + '-' + nowDay + "</b></span></div>";

    printAreaElement += "<table border='1' align='center' cellpadding='1' cellspacing='0' bordercolor='#000000'>";

    //加载列
    printAreaElement += "<tr><th rowspan='2' scope='row' style='width: 100px'>课程节次</th><th colspan='7' scope='col'>课程周期</th></tr>";
    printAreaElement += "<tr><th style='width: 150px'>周一</th><th style='width: 150px'>周二</th><th style='width: 150px'>周三</th>" +
        "<th style='width: 150px'>周四</th><th style='width: 150px'>周五</th><th style='width: 150px'>周六</th><th style='width: 150px'>周日</th></tr>";

    // 载入内容
    var rows = printDatagrid.datagrid("getRows"); // 这段代码是获取当前页的所有行。
    for (var j = 0; j < rows.length; j++) {
        printAreaElement += "<tr>";
        printAreaElement += "<td style='text-align: center'>" + rows[j]['courseTime'] + "</td>";
        printAreaElement += fillPrintCourseTableData(rows[j]['mondayCourse']);
        printAreaElement += fillPrintCourseTableData(rows[j]['tuesdayCourse']);
        printAreaElement += fillPrintCourseTableData(rows[j]['wednesdayCourse']);
        printAreaElement += fillPrintCourseTableData(rows[j]['thursdayCourse']);
        printAreaElement += fillPrintCourseTableData(rows[j]['fridayCourse']);
        printAreaElement += fillPrintCourseTableData(rows[j]['saturdayCourse']);
        printAreaElement += fillPrintCourseTableData(rows[j]['sundayCourse']);
        printAreaElement += "</tr>";
    }
    printAreaElement += "</table>";

    printAreaElement += "</div>";
    return printAreaElement;
}
function fillPrintCourseTableData(weekCourseData) {
    var printCourseWeekCell = "<td style='text-align: center;width: 100px;'>";
    if (weekCourseData) {
        if (weekCourseData.courseName != undefined && weekCourseData.courseName != null) {
            printCourseWeekCell += weekCourseData.courseName;
            if (weekCourseData.teacherName != undefined && weekCourseData.teacherName != null) {
                printCourseWeekCell += "<br><span style='color:#888;font-size: 10px'>授课老师：" + weekCourseData.teacherName + "</span>";
            }
            if (weekCourseData.classroomLocation != undefined && weekCourseData.classroomLocation != null) {
                printCourseWeekCell += "<br><span style='color:#888;font-size: 10px'>授课地点：" + weekCourseData.classroomLocation + "</span>";
            }
        }
    }
    printCourseWeekCell += "</td>";
    return printCourseWeekCell;
}

//初始化选课课程表
function initialCourseTable() {
    $("#course_table").datagrid({
        fit: true,
        rownumbers: false,
        singleSelect: true,
        pagination: false,
        title: "选课课程表",
        url: 'elective/list/table',
        toolbar: '#tb',
        columns: [
            [
                {field: "courseTime", width: 100, align: 'center', title: '课程节次', rowspan: 2},
                {align: 'center', title: '课程周期', colspan: 7}
            ],
            [
                {field: "mondayCourse", width: 150, align: 'center', title: '周一', formatter: weekElectiveCourseFormatter},
                {field: "tuesdayCourse", width: 150, align: 'center', title: '周二', formatter: weekElectiveCourseFormatter},
                {field: "wednesdayCourse", width: 150, align: 'center', title: '周三', formatter: weekElectiveCourseFormatter},
                {field: "thursdayCourse", width: 150, align: 'center', title: '周四', formatter: weekElectiveCourseFormatter},
                {field: "fridayCourse", width: 150, align: 'center', title: '周五', formatter: weekElectiveCourseFormatter},
                {field: "saturdayCourse", width: 150, align: 'center', title: '周六', formatter: weekElectiveCourseFormatter},
                {field: "sundayCourse", width: 150, align: 'center', title: '周日', formatter: weekElectiveCourseFormatter}
            ]
        ],
        onClickCell: courseTableClickCell,
        onClickRow: function (rowIndex, rowData) {
            var panel = $('#course_table').datagrid('getPanel');
            var tr = panel.find('div.datagrid-body tr[datagrid-row-index="' + rowIndex + '"]');
            tr.removeClass("datagrid-row-selected");
        }
    });
};

function initialSouthLayoutContent() {
    if (isElective == "true") {
        initialCourseElectiveTable();
    } else {
        initialCourseStudyTable();
    }
};

//初始化可选课程列表
function initialCourseElectiveTable() {
    $("#course_elective_table").datagrid({
        fit: true,
        rownumbers: false,
        singleSelect: true,
        pagination: true,
        pageSize: 10,
        view: detailview,
        detailFormatter: function (index, row) {
            return '<div id="ddv-' + index + '" style="padding:5px 0"></div>';
        },
        onExpandRow: function (index, row) {
            $('#ddv-' + index).panel({
                height: 180,
                border: false,
                cache: false,
                href: 'elective/course/info/' + row.courseId + '/teacher/' + row.teacherId + '?t=' + (new Date().valueOf()),
                onLoad: function () {
                    $('#course_elective_table').datagrid('fixDetailRowHeight', index);
                }
            });
            $('#course_elective_table').datagrid('fixDetailRowHeight', index);
        },
        rowStyler: function (index, row) {
            if (row.required == 1) {
                return 'color:red;';
            }
        },
        toolbar: [
            {
                text: '清空所选课程',
                iconCls: 'icon-cut',
                handler: function () {

                    if ((courseRow_time == undefined) || (courseRow_week == undefined)) {
                        $.messager.alert("操作提示", "请先单击课程表", "warning");
                    } else {
                        var courseRows = $("#course_table").datagrid("getData");
                        var courseCell = courseRows.rows[courseRow_time][courseRow_week];
                        if (courseCell.id != 0) {
                            $.ajax({
                                type: "POST",
                                url: "elective/delete/" + courseCell.id,
                                dataType: "json",
                                cache: false,
                                success: function (data) {
                                    if (data) {
                                        $("#course_table").datagrid("reload");
                                        $("#course_elective_table").datagrid("loadData",[]);
                                    }
                                }
                            });
                        }
                    }
                }
            }
        ],
        columns: [
            [
                {field: "courseName", width: 150, align: 'center', title: '课程名称'},
                {field: "teacherName", width: 150, align: 'center', title: '授课老师'},
                {field: "classroomLocation", width: 150, align: 'center', title: '授课地点'},
                {field: "restrictionNum", width: 150, align: 'center', title: '开班人数'},
                {field: "currentNum", width: 150, align: 'center', title: '当前人数'},
                {field: "courseSchedulingId", width: 150, align: 'center', formatter: electiveStatusFormatter}
            ]
        ],
        loadFilter: pageLoadFilter
    });
}

//初始化课程学习表
function initialCourseStudyTable() {
    $("#log_tabs").tabs({
        fit: true,
        onSelect: function (title, index) {
            var logTable = undefined;
            var logType = 0;
            switch (index) {
                case 0:
                    logType = 1;
                    logTable = $("#attendanceLog");
                    break;
                case 1:
                    logType = 2;
                    logTable = $("#behaviorLog");
                    break;
                case 2:
                    logType = 3;
                    logTable = $("#homeworkLog");
                    break;
                case 3:
                    logType = 4;
                    logTable = $("#examLog");
                    break;
            }
            initialLogTable(logTable,"study/list/course/" + scheduleId + "/log/" + electiveWeek + "/" + electiveTime + "/" + logType);
//            $.ajax({
//                type: "GET",
//                url: "study/list/course/" + scheduleId + "/log/" + electiveWeek + "/" + electiveTime + "/" + logType,
//                dataType: "json",
//                cache: false,
//                success: function (data) {
//                    initialLogTable(logTable);
//                    logTable.datagrid("loadData", data);
//                }
//            });
        }
    });
    $("#log_tabs").tabs("add", {
        title: "出勤记录",
        closable: false,
        content: "<table id='attendanceLog'></table>"
    });
    $("#log_tabs").tabs("add", {
        title: "课堂表现记录",
        closable: false,
        content: "<table id='behaviorLog'></table>"
    });
    $("#log_tabs").tabs("add", {
        title: "作业记录",
        closable: false,
        content: "<table id='homeworkLog'></table>"
    });
    $("#log_tabs").tabs("add", {
        title: "测验记录",
        closable: false,
        content: "<table id='examLog'></table>"
    });
}

function initialLogTable(logTable,url) {
    logTable.datagrid({
        fit: true,
        rownumbers: false,
        url:url,
        singleSelect: true,
        pagination: true,
        pageSize: 10,
        columns: [
            [
                {field: "logDate", width: 150, align: 'center', title: '记录时间'},
                {field: "logValue", width: 150, align: 'center', title: '是否合格', formatter: booleanFormatter},
                {field: "logContent", width: 250, align: 'center', title: '记录内容'}
            ]
        ],
        rowStyler: function (index, row) {
            if (row.logValue == 0) {
                return 'color:red;';
            }
        },
        loadFilter: pageLoadFilter
    });
}

//点击选课课程表单元格事件处理
function courseTableClickCell(rowIndex, field, value) {
    if (field == "courseTime" || $("#course_elective_table") == null) {
        return;
    }

    var panel = $('#course_table').datagrid('getPanel');
    var selectTd = panel.find('div.datagrid-body tr td.datagrid-row-selected');
    selectTd.removeClass("datagrid-row-selected");
    var tr = panel.find('div.datagrid-body tr[datagrid-row-index="' + rowIndex + '"]');
    tr.each(function () {
        //添加选择的单元格样式
        var td = tr.children('td[field="' + field + '"]');
        td.addClass("datagrid-row-selected");
    });

    electiveWeek = {
        mondayCourse: 1,
        tuesdayCourse: 2,
        wednesdayCourse: 4,
        thursdayCourse: 8,
        fridayCourse: 16,
        saturdayCourse: 32,
        sundayCourse: 64
    }[field] || 0;
    var weekTitle = {
        mondayCourse: "周一",
        tuesdayCourse: "周二",
        wednesdayCourse: "周三",
        thursdayCourse: "周四",
        fridayCourse: "周五",
        saturdayCourse: "周六",
        sundayCourse: "周日"
    }[field] || "";
    var timeTitle = $("#course_table").datagrid("getRows")[rowIndex]["courseTime"];
    electiveTime = {
        "第一节课": 1,
        "第二节课": 2,
        "第三节课": 4,
        "第四节课": 8,
        "第五节课": 16,
        "第六节课": 32,
        "第七节课": 64,
        "第八节课": 128
    }[timeTitle] || 0;

    courseRow_time = rowIndex;
    courseRow_week = {
        1: "mondayCourse",
        2: "tuesdayCourse",
        4: "wednesdayCourse",
        8: "thursdayCourse",
        16: "fridayCourse",
        32: "saturdayCourse",
        64: "sundayCourse"
    }[electiveWeek] || undefined;

    electiveCourseId=value.id;

    scheduleId = value.scheduleId;

    if (isElective == "true") {
        loadCourseElectiveTableData(electiveWeek, electiveTime);
        $("#elective_layout").layout("panel", "south")
            .panel("setTitle", "可选课程列表-" + weekTitle + "(" + timeTitle + ")");
    } else {
        $("#elective_layout").layout("panel", "south")
            .panel("setTitle", "课程学习情况-" + weekTitle + "(" + timeTitle + ")");
        $("#log_tabs").tabs("select", 0);
    }

};

//选课课表格式
function weekElectiveCourseFormatter(value, row, index) {
    var returnValue = "";
    if (value) {
        var courseName = value.courseName;
        var teacherName = value.teacherName;
        var classroomLocation = value.classroomLocation;
        if (courseName) {
            returnValue = "<span style='font-weight:bold'>" + courseName + "</span>";
            if (teacherName) {
                returnValue += "<br><span style='color:#888'>授课老师：" + teacherName + "</span>";
            }
            if (classroomLocation) {
                returnValue += "<br><span style='color:#888'>授课地点：" + classroomLocation + "</span>";
            }
        }
    }
    return  returnValue;
};

//选课数据记录变量
var courseRow_time = 0;
var courseRow_week =undefined;

//“可选课程列表”选课状态格式
function electiveStatusFormatter(value, row, index) {
    $("#course_elective_table").oneTime("0.2s", function () {
        $("#course_select_button_" + index).linkbutton({
            iconCls: "icon-ok",
            plain: true
        }).click(function () {


                var ajaxUrl = "";
                if (scheduleId == 0) {
                    ajaxUrl = "elective/add/" + row.courseSchedulingId + "/" + electiveWeek + "/" + electiveTime;
                } else {
                    ajaxUrl = "elective/update/" + electiveCourseId + "/" + row.courseSchedulingId;
                }
                $.ajax({
                    type: "POST",
                    url:"elective/isElectable/" + row.courseSchedulingId + "/" + electiveWeek + "/" + electiveTime,
                    dataType: "json",
                    cache: false,
                    success: function (isMore) {
                        if(isMore){

                            $.ajax({
                                type: "POST",
                                url: ajaxUrl,
                                dataType: "json",
                                cache: false,
                                success: function (data) {
                                    if (data) {
                                        $("#course_table").datagrid("reload");
                                        $("#course_elective_table").datagrid("loadData",[]);
                                    }
                                }
                            });
                        } else{
                            $.messager.alert("选课提示", "你所选的课程已超过人数上限", "warning");
                            loadCourseElectiveTableData(electiveWeek, electiveTime);
                        }

                    }
                });
            }
        );
    });
    if (row) {
        return "<a id='course_select_button_" + index + "'>";
    }
};

function loadCourseElectiveTableData(week, time) {
    $("#course_elective_table").datagrid("loadData",[]);
    $("#course_elective_table").datagrid("options").pageNumber = 1;
    $("#course_elective_table").datagrid('getPager').pagination({pageNumber: 1});
    $("#course_elective_table").datagrid({
        url: "elective/list/course/" + week + "/" + time
    });
//    $.ajax({
//        type: "GET",
//        url: "elective/list/course/" + week + "/" + time,
//        dataType: "json",
//        cache: false,
//        success: function (data) {
//            $("#course_elective_table").datagrid("loaded");
//            $("#course_elective_table").datagrid("loadData", data);
//        },
//        onload:function(){
//            $("#course_elective_table").datagrid("loading");
//        },
//        onerror:function(){
//            $("#course_elective_table").datagrid("loaded");
//        }
//    });
};

//布尔值格式化显示
function booleanFormatter(value, row, index) {
    if (String(value) == "1") {
        return "是";
    }
    return "否";
};

$.extend($.fn.layout.methods, {
    setRegionToolVisibleState: function (jq, params) {
        return jq.each(function () {
            if (params.region == "center")
                return;
            var panels = $.data(this, 'layout').panels;
            var panel = panels[params.region];
            var tool = panel.panel('header').find('>div.panel-tool');
            tool.css({display: params.visible ? 'block' : 'none'});
            var first = params.region.substring(0, 1);
            var others = params.region.substring(1);
            var expand = 'expand' + first.toUpperCase() + others;
            if (panels[expand]) {
                panels[expand].panel('header').find('>div.panel-tool').css({display: params.visible ? 'block' : 'none'});
            }
        });
    }
});